/**
 * 5. 最长回文子串
 * https://leetcode-cn.com/problems/longest-palindromic-substring/
 */

/**
 * @param {string} s
 * @param {number} index
 * @return {{ length: number, str: string }}
 */
function getPalindromeAt(s, index) {
  const sLength = s.length;
  let begin = Math.floor(index);
  let end = Math.ceil(index);
  while (begin >= 0 && end < sLength) {
    if (s.charCodeAt(begin) !== s.charCodeAt(end)) {
      break;
    }
    begin -= 1;
    end += 1;
  }
  const str = s.substring(begin + 1, end);
  return {
    str,
    length: str.length,
  };
}

/**
 * @param {string} s
 * @return {string}
 */
function longestPalindrome(s) {
  const sLength = s.length;
  let maxLength = 1;
  let maxStr = s.substring(0, 1);
  let loopEnd = sLength - Math.floor(maxLength / 2);
  for (let i = 1; i < loopEnd; i += 1) {
    const res1 = getPalindromeAt(s, i);
    const res2 = getPalindromeAt(s, i - 0.5);
    const { length, str } = res1.length > res2.length ? res1 : res2;
    if (length > maxLength) {
      maxLength = length;
      maxStr = str;
      loopEnd = sLength - Math.floor(maxLength / 2);
    }
  }
  return maxStr;
}

console.log(longestPalindrome('babad') === 'bab');
console.log(longestPalindrome('cbbd') === 'bb');
console.log(longestPalindrome('a') === 'a');
console.log(longestPalindrome('ac') === 'a');
console.log(longestPalindrome('bb') === 'bb');
console.log(longestPalindrome('aaaa') === 'aaaa');
